package com.gitee.cashzhang27.test.boot.reactive.webflux.dao;

import com.gitee.cashzhang27.test.boot.reactive.webflux.entity.City;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Repository;

/**
 * 数据访问层，负责数据的crud
 *
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/03/28 15:31
 */
@Repository
public class CityMapRepository {

  /**
   * 保存数据的集合，作为伪数据库
   */
  private ConcurrentMap<Long, City> repository = new ConcurrentHashMap<>();

  /**
   * id生成器
   */
  private static final AtomicLong ID_GENERATOR = new AtomicLong(0);

  public Long save(City city) {
    Long id = ID_GENERATOR.incrementAndGet();
    city.setId(id);
    repository.put(id, city);
    return id;
  }

  public Collection<City> findAll() {
    return repository.values();
  }


  public City findCityById(Long id) {
    return repository.get(id);
  }

  public Long updateCity(City city) {
    repository.put(city.getId(), city);
    return city.getId();
  }

  public Long deleteCity(Long id) {
    repository.remove(id);
    return id;
  }
}